<template>
  <div class="difficulty-container">
    <!-- 用户信息卡片 -->
    <div class="user-info-bar">
      <el-card class="user-card" shadow="hover">
        <div class="user-profile">
          <div class="avatar">
            <span class="avatar-text">{{ userInitial }}</span>
          </div>
          <div class="user-details">
            <div class="user-header">
              <h3>{{ username }}</h3>
              <el-dropdown trigger="click" @command="handleCommand">
                <span class="el-dropdown-link">
                  <i class="el-icon-setting"></i>
                </span>
                <el-dropdown-menu slot="dropdown">
                  <el-dropdown-item command="history">
                    <i class="el-icon-document"></i> 训练记录
                  </el-dropdown-item>
                  <el-dropdown-item command="logout" divided>
                    <i class="el-icon-switch-button"></i> 退出登录
                  </el-dropdown-item>
                </el-dropdown-menu>
              </el-dropdown>
            </div>
            <!-- <div class="stats">
              <div class="stat-item">
                <span class="stat-label">总训练次数</span>
                <span class="stat-value">{{ totalPractices }}</span>
              </div>
              <div class="stat-item">
                <span class="stat-label">完成题目</span>
                <span class="stat-value">{{ totalQuestions }}</span>
              </div>
              <div class="stat-item">
                <span class="stat-label">正确率</span>
                <span class="stat-value">{{ accuracy }}%</span>
              </div>
            </div>-->
          </div>
        </div>
      </el-card>
    </div>

    <div class="page-title">
      <h1>口算练习</h1>
      <p>选择适合你的难度开始练习吧！</p>
    </div>

    <el-row :gutter="40" class="difficulty-row">
      <el-col :span="12">
        <el-card class="difficulty-card" shadow="hover">
          <template #header>
            <h2>选择难度</h2>
          </template>
          <el-radio-group
            v-model="selectedDifficulty"
            class="difficulty-options"
          >
            <el-radio-button label="easy">
              <div class="option-content">
                <i class="el-icon-star-off"></i>
                <span>简单</span>
              </div>
            </el-radio-button>
            <el-radio-button label="medium">
              <div class="option-content">
                <i class="el-icon-star-on"></i>
                <span>中等</span>
              </div>
            </el-radio-button>
            <el-radio-button label="hard">
              <div class="option-content">
                <i class="el-icon-star-on"></i>
                <i class="el-icon-star-on"></i>
                <span>困难</span>
              </div>
            </el-radio-button>
            <el-radio-button label="skill">
              <div class="option-content">
                <i class="el-icon-trophy"></i>
                <span>技巧训练</span>
              </div>
            </el-radio-button>
          </el-radio-group>

          <div
            class="difficulty-description"
            :class="{ 'no-selection': !selectedDifficulty }"
          >
            <template v-if="selectedDifficulty">
              <template v-if="selectedDifficulty === 'easy'">
                <h3><i class="el-icon-star-off"></i> 简单难度</h3>
                <p>20以内的加减法</p>
                <p>适合：刚开始练习的学生</p>
              </template>

              <template v-else-if="selectedDifficulty === 'medium'">
                <h3><i class="el-icon-star-on"></i> 中等难度</h3>
                <p>100以内加减法以及简单乘除</p>
                <p>适合：已掌握基础运算的学生</p>
              </template>

              <template v-else-if="selectedDifficulty === 'hard'">
                <h3>
                  <i class="el-icon-star-on"></i
                  ><i class="el-icon-star-on"></i> 困难难度
                </h3>
                <p>2位数乘除法以及少量加减</p>
                <p>适合：想要挑战自己的学生</p>
              </template>

              <template v-else-if="selectedDifficulty === 'skill'">
                <h3><i class="el-icon-trophy"></i> 技巧训练</h3>
                <p>1. 尾数为1或9的2位数乘法</p>
                <p>2. 25与4倍数的乘法</p>
                <p>适合：想要学习特殊算法的学生</p>
              </template>
            </template>
            <template v-else>
              <div class="default-description">
                <img
                  src="../assets/math-icon.svg"
                  alt="Math Icon"
                  class="math-icon"
                />
                <h3>请选择练习难度</h3>
                <p>选择一个适合你当前水平的难度开始练习</p>
              </div>
            </template>
          </div>
        </el-card>
      </el-col>

      <el-col :span="12">
        <el-card class="options-card" shadow="hover">
          <template #header>
            <h2>训练设置</h2>
          </template>

          <div class="training-options">
            <h3>题目数量</h3>
            <el-radio-group v-model="questionCount" class="count-options">
              <el-radio-button :label="10">
                <div class="option-content">
                  <span class="number">10</span>
                  <span class="unit">题</span>
                </div>
              </el-radio-button>
              <el-radio-button :label="20">
                <div class="option-content">
                  <span class="number">20</span>
                  <span class="unit">题</span>
                </div>
              </el-radio-button>
              <el-radio-button :label="50">
                <div class="option-content">
                  <span class="number">50</span>
                  <span class="unit">题</span>
                </div>
              </el-radio-button>
            </el-radio-group>

            <template v-if="selectedDifficulty === 'skill'">
              <h3>训练类型</h3>
              <el-radio-group v-model="skillType" class="skill-options">
                <el-radio-button label="type1">
                  <div class="option-content">
                    <i class="el-icon-medal"></i>
                    <span>尾数为1或9的2位数乘法</span>
                  </div>
                </el-radio-button>
                <el-radio-button label="type2">
                  <div class="option-content">
                    <i class="el-icon-medal-1"></i>
                    <span>2.25与4倍数的乘法</span>
                  </div>
                </el-radio-button>
              </el-radio-group>
            </template>

            <div class="start-section">
              <el-button
                type="primary"
                size="large"
                @click="startPractice"
                :disabled="!canStart"
                class="start-button"
              >
                <i class="el-icon-video-play"></i>
                开始训练
              </el-button>
            </div>
          </div>
        </el-card>
      </el-col>
    </el-row>

    <!-- 训练记录对话框 -->
    <el-dialog
      title="训练记录"
      :visible.sync="historyDialogVisible"
      width="80%"
      custom-class="history-dialog"
    >
      <!-- 添加历史趋势图表 -->
      <div class="history-trends">
        <el-card class="trend-card">
          <div slot="header">
            <div class="card-header">
              <span>历史趋势分析</span>
              <el-tooltip
                content="展示每次练习的正确率和平均答题速度变化"
                placement="top"
              >
                <i class="el-icon-info"></i>
              </el-tooltip>
            </div>
          </div>
          <div class="trend-charts">
            <div ref="historyChart" style="height: 400px; width: 100%"></div>
          </div>
        </el-card>
      </div>

      <el-table :data="trainingHistory" style="width: 100%; margin-top: 20px">
        <el-table-column prop="date" label="日期" width="180">
          <template slot-scope="scope">
            {{ formatDate(scope.row.date) }}
          </template>
        </el-table-column>
        <el-table-column prop="difficulty" label="难度" width="100">
          <template slot-scope="scope">
            <el-tag :type="getDifficultyType(scope.row.difficulty)">
              {{ getDifficultyLabel(scope.row.difficulty) }}
            </el-tag>
          </template>
        </el-table-column>
        <el-table-column prop="questionCount" label="题目数量" width="100" />
        <el-table-column prop="correctCount" label="正确数量" width="100" />
        <el-table-column prop="accuracy" label="正确率" width="120">
          <template slot-scope="scope">
            <el-progress
              :percentage="Number(scope.row.accuracy)"
              :color="getColorForAccuracy(Number(scope.row.accuracy))"
            />
          </template>
        </el-table-column>
        <el-table-column label="操作" width="100">
          <template slot-scope="scope">
            <el-button type="text" @click="showAnalysis(scope.row)">
              查看分析
            </el-button>
          </template>
        </el-table-column>
      </el-table>
    </el-dialog>

    <!-- AI分析对话框 -->
    <el-dialog
      title="练习分析"
      :visible.sync="analysisDialogVisible"
      width="70%"
      custom-class="analysis-dialog"
      append-to-body
    >
      <template v-if="currentAnalysis">
        <div class="analysis-content">
          <!-- 统计卡片行 -->
          <el-row :gutter="20" class="stat-row">
            <el-col :span="8">
              <el-card shadow="hover" class="stat-card">
                <div class="stat-item">
                  <div class="stat-title">总体正确率</div>
                  <div class="stat-value">
                    {{ calculateOverallAccuracy() }}%
                  </div>
                </div>
              </el-card>
            </el-col>
            <el-col :span="8">
              <el-card shadow="hover" class="stat-card">
                <div class="stat-item">
                  <div class="stat-title">平均答题速度</div>
                  <div class="stat-value">
                    {{ calculateAverageSpeed() }}秒/题
                  </div>
                </div>
              </el-card>
            </el-col>
            <el-col :span="8">
              <el-card shadow="hover" class="stat-card">
                <div class="stat-item">
                  <div class="stat-title">完成题目数</div>
                  <div class="stat-value">
                    {{ calculateTotalQuestions() }}题
                  </div>
                </div>
              </el-card>
            </el-col>
          </el-row>

          <el-card class="analysis-card">
            <div slot="header">
              <span>练习概况</span>
            </div>
            <div class="practice-summary">
              <div class="summary-item">
                <span class="label">总用时：</span>
                <span class="value">{{ currentRecord.totalTime }}秒</span>
              </div>
              <div class="summary-item">
                <span class="label">题目数量：</span>
                <span class="value">{{ currentRecord.questionCount }}题</span>
              </div>
              <div class="summary-item">
                <span class="label">平均用时：</span>
                <span class="value"
                  >{{
                    (
                      currentRecord.totalTime / currentRecord.questionCount
                    ).toFixed(1)
                  }}秒/题</span
                >
              </div>
            </div>
          </el-card>

          <!-- 趋势分析卡片 -->
          <el-card class="analysis-card mt-20">
            <div slot="header">
              <span>答题趋势</span>
            </div>
            <div class="trend-charts">
              <div class="chart-container">
                <h4>正确率趋势</h4>
                <div ref="accuracyChart" style="height: 250px"></div>
              </div>
              <div class="chart-container">
                <h4>答题速度趋势</h4>
                <div ref="speedChart" style="height: 250px"></div>
              </div>
            </div>
          </el-card>

          <!-- 题型分析卡片 -->
          <el-card class="analysis-card mt-20">
            <div slot="header">
              <span>题型分析</span>
            </div>
            <div class="type-analysis">
              <div ref="questionTypeChart" style="height: 300px"></div>
            </div>
          </el-card>

          <el-card class="analysis-card mt-20">
            <div slot="header">
              <span>题目详情</span>
            </div>
            <el-table :data="currentRecord.questions" style="width: 100%">
              <el-table-column prop="questionType" label="题型" width="120">
                <template slot-scope="scope">
                  {{ getQuestionTypeLabel(scope.row.questionType) }}
                </template>
              </el-table-column>
              <el-table-column prop="question" label="题目" />
              <el-table-column prop="userAnswer" label="你的答案" width="100" />
              <el-table-column
                prop="correctAnswer"
                label="正确答案"
                width="100"
              />
              <el-table-column prop="timeSpent" label="用时(秒)" width="100" />
              <el-table-column label="结果" width="80">
                <template slot-scope="scope">
                  <el-tag :type="scope.row.isCorrect ? 'success' : 'danger'">
                    {{ scope.row.isCorrect ? "正确" : "错误" }}
                  </el-tag>
                </template>
              </el-table-column>
            </el-table>
          </el-card>

          <el-card
            class="analysis-card mt-20"
            v-if="
              currentRecord.analysis && currentRecord.analysis.analysisContent
            "
          >
            <div slot="header">
              <span>AI 分析建议</span>
            </div>
            <div class="ai-analysis">
              <i class="el-icon-chat-dot-round analysis-icon"></i>
              <div class="analysis-text">
                {{ currentRecord.analysis.analysisContent }}
              </div>
            </div>
          </el-card>
        </div>
      </template>
    </el-dialog>
  </div>
</template>

<script>
import { getPracticeHistory } from "../api/practice";
import * as echarts from "echarts";

export default {
  name: "DifficultySelect",
  data() {
    return {
      selectedDifficulty: "",
      questionCount: 10,
      skillType: "type1",
      username: localStorage.getItem("username") || "用户",
      historyDialogVisible: false,
      trainingHistory: [],
      totalPractices: 0,
      totalQuestions: 0,
      accuracy: 0,
      analysisDialogVisible: false,
      currentAnalysis: null,
      currentRecord: null,
      charts: {
        accuracyChart: null,
        speedChart: null,
        questionTypeChart: null,
      },
    };
  },
  computed: {
    canStart() {
      return this.selectedDifficulty && this.questionCount;
    },
    userInitial() {
      return this.username.charAt(0).toUpperCase();
    },
  },
  created() {
    this.loadUserStats();
    this.loadTrainingHistory();
  },
  methods: {
    startPractice() {
      this.$router.push({
        name: "Practice",
        query: {
          difficulty: this.selectedDifficulty,
          count: this.questionCount,
          skillType:
            this.selectedDifficulty === "skill" ? this.skillType : undefined,
        },
      });
    },
    loadUserStats() {
      // 从 localStorage 加载用户统计数据
      const stats = JSON.parse(localStorage.getItem("userStats") || "{}");
      this.totalPractices = stats.totalPractices || 0;
      this.totalQuestions = stats.totalQuestions || 0;
      this.accuracy = stats.accuracy || 0;
    },
    loadTrainingHistory() {
      console.log("开始加载训练历史...");
      getPracticeHistory()
        .then((response) => {
          console.log("获取训练历史响应:", response);
          if (response && response.code === 200) {
            console.log("原始训练历史数据:", response.rows);
            try {
              this.trainingHistory = response.rows
                .map((record) => {
                  console.log("处理记录:", record);
                  if (!record.questions) {
                    console.warn("记录缺少questions字段:", record);
                    return null;
                  }

                  const correctCount = record.questions.filter(
                    (q) => q.isCorrect
                  ).length;
                  const accuracy = (
                    (correctCount / record.questionCount) *
                    100
                  ).toFixed(1);
                  const averageTime = (
                    record.totalTime / record.questionCount
                  ).toFixed(1);

                  const processedRecord = {
                    ...record,
                    date:
                      record.startTime ||
                      record.createTime ||
                      record.analysis.createTime,
                    correctCount,
                    accuracy,
                    averageTime,
                  };
                  console.log("处理后的记录:", processedRecord);
                  return processedRecord;
                })
                .filter((record) => record !== null);

              console.log("最终处理后的训练历史:", this.trainingHistory);
              this.$nextTick(() => {
                this.initHistoryChart();
              });
            } catch (error) {
              console.error("处理训练历史数据时出错:", error);
              this.$message.error(`处理训练历史数据时出错: ${error.message}`);
            }
          } else {
            console.error("获取训练历史失败:", response);
            this.$message.error(response?.msg || "获取训练历史失败");
          }
        })
        .catch((error) => {
          console.error("获取训练历史失败:", error);
          if (error.response) {
            console.error("错误响应:", error.response);
            this.$message.error(
              `获取训练历史失败: ${error.response.msg || error.message}`
            );
          } else if (error.request) {
            console.error("请求未收到响应:", error.request);
            this.$message.error("服务器未响应，请检查网络连接");
          } else {
            console.error("请求配置错误:", error.message);
            this.$message.error(`请求错误: ${error.message}`);
          }
        });
    },
    calculateTypeAccuracy(stats) {
      if (!stats || stats.total === 0) return 0;
      return ((stats.correct / stats.total) * 100).toFixed(1);
    },
    generateSuggestions(record) {
      const suggestions = [];
      const questions = record.questions;

      // 分析答题时间趋势
      const timeSpents = questions.map((q) => q.timeSpent);
      const avgTime = timeSpents.reduce((a, b) => a + b, 0) / timeSpents.length;
      if (avgTime > 5) {
        suggestions.push("答题速度较慢，建议加强基础运算能力训练");
      }

      // 分析错误模式
      const errorQuestions = questions.filter((q) => !q.isCorrect);
      if (errorQuestions.length > 0) {
        const errorTypes = {};
        errorQuestions.forEach((q) => {
          errorTypes[q.questionType] = (errorTypes[q.questionType] || 0) + 1;
        });

        // 找出错误最多的题型
        const maxErrorType = Object.entries(errorTypes).reduce((a, b) =>
          a[1] > b[1] ? a : b
        )[0];

        const typeMap = {
          add: "加法",
          subtract: "减法",
          multiply: "乘法",
          divide: "除法",
        };

        suggestions.push(
          `${typeMap[maxErrorType]}题目正确率较低，需要加强练习`
        );
      }

      // 分析答案规律
      const repeatedAnswers = questions.filter((q, i, arr) =>
        arr.slice(i + 1).some((next) => q.userAnswer === next.userAnswer)
      );

      if (repeatedAnswers.length > 3) {
        suggestions.push("发现重复答案，请认真思考每道题目");
      }

      // 分析答题时间变化
      const timeChanges = timeSpents
        .slice(1)
        .map((time, i) => time - timeSpents[i]);
      const increasingTime = timeChanges.filter((change) => change > 2).length;
      if (increasingTime > timeChanges.length / 2) {
        suggestions.push("答题时间逐渐增加，可能出现疲劳，建议适当休息");
      }

      return suggestions;
    },
    showAnalysis(record) {
      this.currentRecord = record;
      this.currentAnalysis = record.analysis;
      this.analysisDialogVisible = true;
      this.$nextTick(() => {
        this.initCharts();
      });
    },
    initCharts() {
      this.$nextTick(() => {
        this.initAccuracyChart();
        this.initSpeedChart();
        this.initQuestionTypeChart();
      });
    },
    initAccuracyChart() {
      if (!this.currentRecord?.questions) return;

      const chartDom = this.$refs.accuracyChart;
      if (!chartDom) return;

      this.charts.accuracyChart = echarts.init(chartDom);

      const data = this.currentRecord.questions.map((q, index) => [
        index + 1,
        q.isCorrect ? 100 : 0,
      ]);

      const option = {
        tooltip: {
          trigger: "axis",
          formatter: "第{b}题: {c}%",
        },
        xAxis: {
          type: "category",
          name: "题号",
          nameLocation: "middle",
          nameGap: 25,
        },
        yAxis: {
          type: "value",
          name: "正确率(%)",
          max: 100,
        },
        series: [
          {
            data: data,
            type: "line",
            smooth: true,
            lineStyle: { color: "#409EFF" },
            areaStyle: {
              color: new echarts.graphic.LinearGradient(0, 0, 0, 1, [
                {
                  offset: 0,
                  color: "rgba(64,158,255,0.3)",
                },
                {
                  offset: 1,
                  color: "rgba(64,158,255,0.1)",
                },
              ]),
            },
          },
        ],
      };

      this.charts.accuracyChart.setOption(option);
    },
    initSpeedChart() {
      if (!this.currentRecord?.questions) return;

      const chartDom = this.$refs.speedChart;
      if (!chartDom) return;

      this.charts.speedChart = echarts.init(chartDom);

      const data = this.currentRecord.questions.map((q, index) => [
        index + 1,
        q.timeSpent,
      ]);

      const option = {
        tooltip: {
          trigger: "axis",
          formatter: "第{b}题: {c}秒",
        },
        xAxis: {
          type: "category",
          name: "题号",
          nameLocation: "middle",
          nameGap: 25,
        },
        yAxis: {
          type: "value",
          name: "用时(秒)",
        },
        series: [
          {
            data: data,
            type: "line",
            smooth: true,
            lineStyle: { color: "#67C23A" },
            areaStyle: {
              color: new echarts.graphic.LinearGradient(0, 0, 0, 1, [
                {
                  offset: 0,
                  color: "rgba(103,194,58,0.3)",
                },
                {
                  offset: 1,
                  color: "rgba(103,194,58,0.1)",
                },
              ]),
            },
          },
        ],
      };

      this.charts.speedChart.setOption(option);
    },
    initQuestionTypeChart() {
      if (!this.currentRecord?.questions) return;

      const chartDom = this.$refs.questionTypeChart;
      if (!chartDom) return;

      this.charts.questionTypeChart = echarts.init(chartDom);

      // 统计各题型数据
      const typeStats = {};
      this.currentRecord.questions.forEach((q) => {
        if (!typeStats[q.questionType]) {
          typeStats[q.questionType] = {
            total: 0,
            correct: 0,
          };
        }
        typeStats[q.questionType].total++;
        if (q.isCorrect) {
          typeStats[q.questionType].correct++;
        }
      });

      const typeLabels = {
        add: "加法",
        subtract: "减法",
        multiply: "乘法",
        divide: "除法",
      };

      const data = Object.entries(typeStats).map(([type, stats]) => ({
        name: typeLabels[type] || type,
        value: ((stats.correct / stats.total) * 100).toFixed(1),
        itemStyle: {
          color:
            type === "add"
              ? "#409EFF"
              : type === "subtract"
              ? "#67C23A"
              : type === "multiply"
              ? "#E6A23C"
              : "#F56C6C",
        },
      }));

      const option = {
        tooltip: {
          trigger: "item",
          formatter: "{b}: {c}%",
        },
        series: [
          {
            type: "pie",
            radius: ["40%", "70%"],
            avoidLabelOverlap: false,
            label: {
              show: true,
              formatter: "{b}\n{c}%",
            },
            emphasis: {
              label: {
                show: true,
                fontSize: "16",
                fontWeight: "bold",
              },
            },
            data: data,
          },
        ],
      };

      this.charts.questionTypeChart.setOption(option);
    },
    getQuestionTypeLabel(type) {
      const typeMap = {
        add: "加法",
        subtract: "减法",
        multiply: "乘法",
        divide: "除法",
      };
      return typeMap[type] || type;
    },
    handleCommand(command) {
      if (command === "history") {
        this.loadTrainingHistory();
        this.historyDialogVisible = true;
      } else if (command === "logout") {
        this.$confirm("确认退出登录吗？", "提示", {
          confirmButtonText: "确定",
          cancelButtonText: "取消",
          type: "warning",
        })
          .then(() => {
            localStorage.removeItem("token");
            localStorage.removeItem("username");
            this.$message.success("已退出登录");
            this.$router.push("/");
          })
          .catch(() => {});
      }
    },
    formatDate(date) {
      return new Date(date).toLocaleString();
    },
    getDifficultyLabel(difficulty) {
      const labels = {
        easy: "简单",
        medium: "中等",
        hard: "困难",
        skill: "技巧",
      };
      return labels[difficulty] || difficulty;
    },
    getDifficultyType(difficulty) {
      const types = {
        easy: "success",
        medium: "warning",
        hard: "danger",
        skill: "info",
      };
      return types[difficulty] || "info";
    },
    getColorForAccuracy(accuracy) {
      if (accuracy >= 90) return "#67C23A";
      if (accuracy >= 70) return "#E6A23C";
      return "#F56C6C";
    },
    calculateOverallAccuracy() {
      if (!this.currentRecord || !this.currentRecord.questions) return "0.0";
      const correctCount = this.currentRecord.questions.filter(
        (q) => q.isCorrect
      ).length;
      return (
        (correctCount / this.currentRecord.questions.length) *
        100
      ).toFixed(1);
    },
    calculateAverageSpeed() {
      if (!this.currentRecord || !this.currentRecord.questions) return "0.0";
      const totalTime = this.currentRecord.questions.reduce(
        (sum, q) => sum + q.timeSpent,
        0
      );
      return (totalTime / this.currentRecord.questions.length).toFixed(1);
    },
    calculateTotalQuestions() {
      return this.currentRecord?.questions?.length || 0;
    },
    initHistoryChart() {
      if (!this.$refs.historyChart) return;

      const chartDom = this.$refs.historyChart;
      const chart = echarts.init(chartDom);

      // 准备数据
      const dates = this.trainingHistory.map((record) =>
        new Date(record.date).toLocaleString("zh-CN", {
          month: "2-digit",
          day: "2-digit",
          hour: "2-digit",
          minute: "2-digit",
        })
      );
      const accuracies = this.trainingHistory.map((record) =>
        Number(record.accuracy)
      );
      const speeds = this.trainingHistory.map((record) =>
        Number(record.averageTime)
      );

      const option = {
        tooltip: {
          trigger: "axis",
          axisPointer: {
            type: "cross",
          },
        },
        legend: {
          data: ["正确率", "平均用时"],
          top: 10,
        },
        grid: {
          left: "3%",
          right: "4%",
          bottom: "3%",
          containLabel: true,
        },
        xAxis: {
          type: "category",
          boundaryGap: false,
          data: dates,
          axisLabel: {
            rotate: 45,
          },
        },
        yAxis: [
          {
            type: "value",
            name: "正确率(%)",
            min: 0,
            max: 100,
            position: "left",
            axisLine: {
              show: true,
              lineStyle: {
                color: "#409EFF",
              },
            },
            axisLabel: {
              formatter: "{value}%",
            },
          },
          {
            type: "value",
            name: "平均用时(秒)",
            min: 0,
            position: "right",
            axisLine: {
              show: true,
              lineStyle: {
                color: "#67C23A",
              },
            },
            axisLabel: {
              formatter: "{value}s",
            },
          },
        ],
        series: [
          {
            name: "正确率",
            type: "line",
            smooth: true,
            data: accuracies,
            itemStyle: {
              color: "#409EFF",
            },
            areaStyle: {
              color: new echarts.graphic.LinearGradient(0, 0, 0, 1, [
                {
                  offset: 0,
                  color: "rgba(64,158,255,0.3)",
                },
                {
                  offset: 1,
                  color: "rgba(64,158,255,0.1)",
                },
              ]),
            },
          },
          {
            name: "平均用时",
            type: "line",
            smooth: true,
            yAxisIndex: 1,
            data: speeds,
            itemStyle: {
              color: "#67C23A",
            },
            areaStyle: {
              color: new echarts.graphic.LinearGradient(0, 0, 0, 1, [
                {
                  offset: 0,
                  color: "rgba(103,194,58,0.3)",
                },
                {
                  offset: 1,
                  color: "rgba(103,194,58,0.1)",
                },
              ]),
            },
          },
        ],
      };

      chart.setOption(option);

      // 监听窗口大小变化
      window.addEventListener("resize", () => {
        chart.resize();
      });

      // 在组件销毁时移除事件监听
      this.$once("hook:beforeDestroy", () => {
        window.removeEventListener("resize", () => {
          chart.resize();
        });
        chart.dispose();
      });
    },
  },
  beforeDestroy() {
    // 销毁图表实例
    Object.values(this.charts).forEach((chart) => {
      if (chart) {
        chart.dispose();
      }
    });
  },
};
</script>

<style scoped>
.difficulty-container {
  max-width: 1400px;
  margin: 0 auto;
  padding: 40px;
  min-height: 100vh;
  background: linear-gradient(135deg, #f0f7ff 0%, #e8f3ff 100%);
  position: relative;
  overflow: hidden;
}

.difficulty-container::before {
  content: "";
  position: absolute;
  top: -50%;
  right: -50%;
  width: 100%;
  height: 100%;
  background: radial-gradient(
    circle,
    rgba(43, 121, 255, 0.1) 0%,
    transparent 60%
  );
  transform: rotate(-45deg);
  z-index: 0;
}

.user-info-bar {
  position: fixed;
  top: 30px;
  right: 30px;
  z-index: 100;
  width: 320px;
}

.difficulty-row {
  margin-top: 120px;
  display: flex;
  justify-content: center;
  gap: 40px;
  position: relative;
  z-index: 1;
}

.el-col {
  max-width: 480px;
  width: 100%;
}

.difficulty-card,
.options-card {
  height: 100%;
  transition: all 0.3s ease;
  border: none;
  border-radius: 20px;
  background: rgba(255, 255, 255, 0.9);
  backdrop-filter: blur(10px);
  box-shadow: 0 10px 30px rgba(43, 121, 255, 0.1);
}

.difficulty-card:hover,
.options-card:hover {
  transform: translateY(-5px);
  box-shadow: 0 8px 25px rgba(43, 121, 255, 0.15);
}

.difficulty-options {
  display: grid;
  grid-template-columns: repeat(2, 1fr);
  gap: 15px;
  margin: 25px 0;
}

.difficulty-options .el-radio-button :deep(.el-radio-button__inner) {
  width: 100%;
  height: 52px;
  line-height: 52px;
  border: 1px solid #e8f3ff;
  background: #fff;
  color: #606266;
  transition: all 0.3s;
  border-radius: 14px;
  font-size: 16px;
  font-weight: 500;
  position: relative;
  overflow: hidden;
  box-shadow: 0 2px 6px rgba(43, 121, 255, 0.05);
}

.difficulty-options .el-radio-button :deep(.el-radio-button__inner:hover) {
  color: #2b79ff;
  border-color: #2b79ff;
  background: #f5f9ff;
  transform: translateY(-2px);
  box-shadow: 0 4px 12px rgba(43, 121, 255, 0.1);
}

.difficulty-options .el-radio-button.is-active :deep(.el-radio-button__inner) {
  background: linear-gradient(120deg, #2b79ff, #5094ff);
  color: #fff;
  border-color: transparent;
  box-shadow: 0 4px 15px rgba(43, 121, 255, 0.2);
}

.difficulty-description {
  margin-top: 30px;
  padding: 30px;
  background-color: #f8faff;
  border-radius: 16px;
  border: 1px solid #e8f3ff;
  position: relative;
  overflow: hidden;
  min-height: 180px;
  display: flex;
  flex-direction: column;
  justify-content: center;
  box-shadow: inset 0 2px 6px rgba(43, 121, 255, 0.05);
  transition: all 0.3s ease;
}

.difficulty-description.no-selection {
  background: linear-gradient(135deg, #f8faff 0%, #f0f7ff 100%);
}

.default-description {
  text-align: center;
  padding: 20px;
}

.math-icon {
  width: 60px;
  height: 60px;
  margin-bottom: 15px;
  opacity: 0.8;
}

.default-description h3 {
  color: #909399;
  font-size: 18px;
  margin: 0 0 10px;
}

.default-description p {
  color: #c0c4cc;
  font-size: 14px;
  margin: 0;
}

.count-options .option-content {
  flex-direction: column;
  gap: 2px;
}

.count-options .number {
  font-size: 20px;
  font-weight: 600;
}

.count-options .unit {
  font-size: 12px;
  opacity: 0.8;
}

.training-options {
  padding: 20px 0;
}

.training-options h3 {
  margin: 0 0 20px 0;
  color: #2b79ff;
  font-size: 18px;
  font-weight: 600;
  display: flex;
  align-items: center;
}

.skill-options {
  margin: 30px 0;
  display: flex;
  justify-content: center;
  gap: 20px;
}

.skill-options .el-radio-button :deep(.el-radio-button__inner) {
  border-radius: 14px;
  padding: 12px 35px;
  height: 48px;
  line-height: 24px;
  border: 1px solid #e8f3ff;
  background: #fff;
  color: #606266;
  transition: all 0.3s;
  font-size: 16px;
  font-weight: 500;
  box-shadow: 0 2px 6px rgba(43, 121, 255, 0.05);
}

.skill-options .el-radio-button :deep(.el-radio-button__inner:hover) {
  color: #2b79ff;
  border-color: #2b79ff;
  background: #f5f9ff;
  transform: translateY(-2px);
  box-shadow: 0 4px 12px rgba(43, 121, 255, 0.1);
}

.skill-options .el-radio-button.is-active :deep(.el-radio-button__inner) {
  background: linear-gradient(120deg, #2b79ff, #5094ff);
  color: #fff;
  border-color: transparent;
  box-shadow: 0 4px 15px rgba(43, 121, 255, 0.2);
}

.start-section {
  margin-top: 40px;
  text-align: center;
}

.start-button {
  width: 260px;
  height: 56px;
  font-size: 18px;
  font-weight: 600;
  border-radius: 16px;
  background: linear-gradient(120deg, #2b79ff, #5094ff);
  border: none;
  color: #fff;
  transition: all 0.3s;
  position: relative;
  overflow: hidden;
  letter-spacing: 1px;
  box-shadow: 0 4px 15px rgba(43, 121, 255, 0.2);
}

.start-button:hover {
  transform: translateY(-2px);
  box-shadow: 0 6px 20px rgba(43, 121, 255, 0.3);
  background: linear-gradient(120deg, #5094ff, #2b79ff);
}

.start-button:disabled {
  background: linear-gradient(120deg, #a0cfff, #c8e1ff);
  border: none;
  transform: none;
  box-shadow: none;
  cursor: not-allowed;
  opacity: 0.7;
}

.el-card :deep(.el-card__header) {
  background-color: #f8faff;
  border-bottom: 1px solid #e8f3ff;
  padding: 25px 30px;
}

.el-card :deep(.el-card__header) h2 {
  margin: 0;
  font-size: 24px;
  font-weight: 600;
  background: linear-gradient(120deg, #2b79ff, #5094ff);
  -webkit-background-clip: text;
  -webkit-text-fill-color: transparent;
  letter-spacing: 0.5px;
}

.el-card :deep(.el-card__body) {
  padding: 30px;
}

.user-info-bar {
  position: fixed;
  top: 20px;
  right: 20px;
  z-index: 100;
  width: 320px;
}

.user-card {
  background: rgba(255, 255, 255, 0.95);
  backdrop-filter: blur(10px);
  border-radius: 16px;
  overflow: hidden;
}

.user-profile {
  display: flex;
  align-items: center;
  gap: 20px;
}

.avatar {
  width: 48px;
  height: 48px;
  border-radius: 50%;
  background: linear-gradient(120deg, #2b79ff, #5094ff);
  display: flex;
  align-items: center;
  justify-content: center;
}

.avatar-text {
  color: #fff;
  font-size: 20px;
  font-weight: 600;
}

.user-details {
  flex: 1;
}

.user-details h3 {
  margin: 0 0 10px 0;
  color: #2b79ff;
  font-size: 18px;
  font-weight: 600;
}

.user-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 12px;
}

.user-header h3 {
  margin: 0;
  color: #2b79ff;
  font-size: 18px;
  font-weight: 600;
}

.el-dropdown-link {
  cursor: pointer;
  color: #909399;
  font-size: 16px;
  transition: color 0.3s;
  padding: 5px;
}

.el-dropdown-link:hover {
  color: #2b79ff;
}

:deep(.el-dropdown-menu) {
  padding: 5px 0;
  border-radius: 8px;
  border: none;
  box-shadow: 0 4px 12px rgba(0, 0, 0, 0.1);
}

:deep(.el-dropdown-menu__item) {
  padding: 8px 16px;
  font-size: 14px;
  line-height: 1.5;
}

:deep(.el-dropdown-menu__item i) {
  margin-right: 8px;
}

:deep(.el-dropdown-menu__item--divided) {
  margin-top: 5px;
  border-top: 1px solid #e8f3ff;
}

:deep(.el-dropdown-menu__item--divided::before) {
  height: 5px;
  background-color: #fff;
}

.stats {
  display: grid;
  grid-template-columns: repeat(3, 1fr);
  gap: 15px;
}

.stat-item {
  text-align: center;
  padding: 8px;
  background: #f8faff;
  border-radius: 8px;
  transition: all 0.3s;
}

.stat-item:hover {
  background: #e8f3ff;
  transform: translateY(-2px);
}

.stat-label {
  display: block;
  font-size: 12px;
  color: #909399;
  margin-bottom: 4px;
}

.stat-value {
  display: block;
  font-size: 16px;
  font-weight: 600;
  color: #2b79ff;
}

.history-dialog {
  border-radius: 16px;
}

:deep(.history-dialog .el-dialog__header) {
  padding: 20px;
  background: #f8faff;
  border-bottom: 1px solid #e8f3ff;
}

:deep(.history-dialog .el-dialog__body) {
  padding: 25px;
}

.el-tag {
  border-radius: 6px;
}

.el-progress {
  margin-right: 20px;
}

.page-title {
  text-align: center;
  margin-bottom: 60px;
  position: relative;
  z-index: 1;
}

.page-title h1 {
  font-size: 36px;
  font-weight: 600;
  margin: 0;
  background: linear-gradient(120deg, #2b79ff, #5094ff);
  -webkit-background-clip: text;
  -webkit-text-fill-color: transparent;
  letter-spacing: 1px;
}

.page-title p {
  font-size: 16px;
  color: #606266;
  margin: 10px 0 0;
  letter-spacing: 0.5px;
}

@media screen and (max-width: 1200px) {
  .difficulty-container {
    padding: 20px;
  }

  .difficulty-row {
    margin-top: 100px;
    gap: 20px;
  }

  .el-col {
    max-width: 450px;
  }
}

@media screen and (max-width: 768px) {
  .difficulty-row {
    flex-direction: column;
    align-items: center;
    margin-top: 80px;
  }

  .el-col {
    width: 100%;
    max-width: 100%;
  }

  .user-info-bar {
    width: calc(100% - 40px);
    top: 20px;
    right: 20px;
  }
}

.analysis-card {
  margin-bottom: 20px;
}

.mt-20 {
  margin-top: 20px;
}

.practice-summary {
  padding: 20px;
}

.summary-item {
  margin-bottom: 15px;
  font-size: 16px;
  display: flex;
  align-items: center;
}

.summary-item .label {
  color: #606266;
  width: 100px;
}

.summary-item .value {
  color: #303133;
  font-weight: 500;
}

.trend-chart {
  width: 100%;
  height: 400px;
  margin: 20px 0;
}

.analysis-dialog {
  .el-dialog__body {
    padding: 20px;
  }
}

.analysis-content {
  padding: 20px;
}

.ai-analysis {
  display: flex;
  align-items: flex-start;
  padding: 20px;
  background-color: #f8f9fa;
  border-radius: 8px;
}

.analysis-icon {
  font-size: 24px;
  color: #409eff;
  margin-right: 15px;
  margin-top: 3px;
}

.analysis-text {
  color: #606266;
  line-height: 1.6;
  font-size: 14px;
  white-space: pre-line;
}

.stat-row {
  margin-bottom: 20px;
}

.stat-card {
  height: 100%;
}

.stat-item {
  text-align: center;
  padding: 15px;
}

.stat-title {
  font-size: 14px;
  color: #909399;
  margin-bottom: 10px;
}

.stat-value {
  font-size: 24px;
  font-weight: bold;
  color: #303133;
}

.trend-charts {
  display: grid;
  grid-template-columns: 1fr 1fr;
  gap: 20px;
  padding: 10px;
}

.chart-container {
  background: #fff;
  border-radius: 4px;
}

.chart-container h4 {
  margin: 0 0 15px 0;
  padding: 10px;
  color: #303133;
  font-size: 14px;
  border-bottom: 1px solid #ebeef5;
}

.type-analysis {
  padding: 10px;
}

.history-trends {
  margin-bottom: 20px;
}

.trend-card {
  background: #fff;
  border-radius: 8px;
}

.card-header {
  display: flex;
  align-items: center;
  gap: 8px;
}

.card-header i {
  color: #909399;
  cursor: help;
}

.trend-charts {
  padding: 20px;
}
</style>
